package com.zm.demo.core.net;

import sun.net.TelnetInputStream;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author z01140
 * @Package: com.zm.demo.core.net
 * @Description:
 * @CreateDate 2022/6/15 11:59
 * @UpdateDate 2022/6/15 11:59
 */
public class NetCheck {

    public static void main(String[] args) {

        System.out.println(telnet("192.168.26.223", 2181, 1000));
        System.out.println(telnet("192.168.26.223", 21811, 1000));

        System.out.println(ping("www.baidu.com",80));
        System.out.println(ping("www.baidu.com",1800));
    }


    public static final boolean telnet(String hostName, int port, int timeout){

        Socket socket = new Socket();
        boolean isConnected = false;
        try {
            System.out.println(String.format("telnet 拨测开始，%s:%s", hostName, port));
            socket.connect(new InetSocketAddress(hostName, port), timeout);
            isConnected = socket.isConnected();
            System.out.println(String.format("telnet 拨测结束，%s:%s，结果：%s", hostName, port, isConnected));
        }catch (Exception e){
            e.printStackTrace();
            isConnected = false;
            System.out.println(String.format("telnet 拨测异常，%s:%s，异常信息：%s", hostName, port, e.getMessage()));
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isConnected;
    }

    public static final boolean ping(String hostName, int port){

        InetSocketAddress socket = null;
        boolean isConnected = false;
        try {
            System.out.println(String.format("ping 拨测开始，%s:%s", hostName, port));
            socket = new InetSocketAddress(hostName, port);
            isConnected = !socket.isUnresolved();
            System.out.println(String.format("ping 拨测结束，%s:%s，结果：%s", hostName, port, isConnected));
        }catch (Exception e){
            e.printStackTrace();
            isConnected = false;
            System.out.println(String.format("ping 拨测异常，%s:%s，异常信息：%s", hostName, port, e.getMessage()));
        }finally {
        }
        return isConnected;
    }
}
